/**
 * Created by tcrow on 2017/1/12 0012.
 */
var module = app;

module.directive('ngConfirmClick', [
    function(){
        return {
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.confirmedClick;
                element.bind('click',function (event) {
                    if ( window.confirm(msg) ) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
    }]);
module.controller('scriptController', ['$scope','$window', 'ngDialog', '$http','Notification',function ($scope,$window, ngDialog, $http,Notification) {
    $scope.paginationConf = {
        currentPage: 1,
        totalItems: 0,
        itemsPerPage: 10,
        pagesLength: 15,
        perPageOptions: [10],
        rememberPerPage: 'perPageItems',
        onChange: function () {
            $scope.showscriptList(this.currentPage,this.totalItems);

        }
    };
    $scope.status=['已废弃','使用中'];
    $scope.changeStatus=['恢复','废弃'];
    $scope.allscriptList = [];
    $scope.scriptShowList = [];
    $scope.filterDistribute = false;
    $scope.filterNomal = false;
    $scope.$watch('filterDistribute', function() {
        $scope.filterList(1);
    });
    $scope.$watch('filterNomal', function() {
    	$scope.filterList(1);
    });
    $http({
        method: "GET",
        url: "script/list.query"
    }).success(function (resp) {
        if(resp.status ==0){
            $scope.allscriptList = resp.data;
            console.log($scope.allscriptList);
            console.log(JSON.stringify(resp));
            $scope.showscriptList(1,$scope.allscriptList.length);

        }else {
            Notification.error({message: resp.errMsg, delay: 5000});
        }

    });
    $http({
        method: "GET",
        url: "topic/getUserSys.query"
    }).success(function (resp) {
        if(resp.status ==0){
            $scope.myuserSys = resp.data;
        }else {
            Notification.error({message: resp.errMsg, delay: 5000});
        }

    });
    	$http({
            method: "GET",
            url: "user/getCurentUser.query"
        }).success(function (resp) {
            if(resp.status ==0){
                $scope.curentUser = resp.data.name;
            }else {
                Notification.error({message: resp.errMsg, delay: 5000});
            }

        });
    $scope.regionCode='';
    $scope.envCode='';
    /**
     * 域名变动,更新环境
     */
    $scope.changeRegion=function(regionCode){
    	$scope.regionCode=regionCode;
    	console.log(regionCode);
    	console.log($scope.ngDialogData.allEnvNameList);
    	
    	 $http({
    	        method: "POST",
    	        url: "script/findEnvCodeByRegionCode.query",
    	        data:regionCode
    	    }).success(function (resp) {
    	    	debugger;
    	        if(resp.status ==0){
    	        	$scope.ngDialogData.allEnvNameList=resp.data.envMap;
    	        }else {
    	            Notification.error({message: resp.errMsg, delay: 5000});
    	        }

    	    });
    }
    
    /**
     * 域名和环境变动更新集群名
     */
    $scope.changeEnv=function(envCode){
    	console.log($scope.regionCode);
    	console.log(envCode);
    	 $http({
 	        method: "POST",
 	        url: "script/findClusterByRegionCodeAndEnvCode.query",
 	       data:{
 	    	  regionCode:$scope.regionCode,
 	    	  envCode:envCode
           }
 	    }).success(function (resp) {
 	        if(resp.status ==0){
 	        	$scope.ngDialogData.allClusterList=resp.data.clusterMap;
 	        }else {
 	            Notification.error({message: resp.errMsg, delay: 5000});
 	        }

 	    });
    }
    $scope.filterStr="";
    $scope.filterVersion="";
    $scope.$watch('filterStr', function() {
        $scope.filterList(1);
    });
    $scope.$watch('filterVersion', function() {
        $scope.filterList(1);
    });
    
    $scope.filterByType = function(str){
        if($scope.filterDistribute  && !$scope.filterNomal){
            if(str.isDistribute==1){
                return true;
            }
        }else  if($scope.filterNomal && !$scope.filterDistribute){
        	if(str.isDistribute==0){
        		return true;
        	}
        }else if($scope.filterDistribute && $scope.filterNomal){
        	 return true;
        }else{
        	return true;
        }
       
    };
    $scope.filterList = function (currentPage) {
        var lowExceptStr =  $scope.filterStr.toLowerCase();
        var lowExceptStrVersion =  $scope.filterVersion.toLowerCase();
        var canShowList = [];
        $scope.allscriptList.forEach(function(element) {
        	var topicName=toString(element.topicName);
        	if($scope.filterByType(element)){
                if (element.topicName.toLowerCase().indexOf(lowExceptStr) != -1 && element.versionCode.toLowerCase().indexOf(lowExceptStrVersion) != -1){
                	if($scope.userSys.length>0){
	                	for ( var i = 0; i <$scope.userSys.length; i++){
	                    	if (element.topicName.toLowerCase().indexOf($scope.userSys[i].toLowerCase()) != -1){
	                    		//canShowList.push(element);
	                    		if(canShowList.indexOf(element) == -1){
	                   			 canShowList.push(element);
	                    		}
	                    	}
	                		if (element.servOfferName.toLowerCase().indexOf($scope.userSys[i].toLowerCase()) != -1){
	                    		//canShowList.push(element);
	                    		if(canShowList.indexOf(element) == -1){
	                   			 canShowList.push(element);
	                    		}
	                    	}
	                	}
	                }else{
                    	canShowList.push(element);
                    }
                }
        	}
         
        });
        $scope.paginationConf.totalItems =canShowList.length;
        var perPage = $scope.paginationConf.itemsPerPage;
        var from = (currentPage - 1) * perPage;
        var to = (from + perPage)>canShowList.length?canShowList.length:from + perPage;
        $scope.scriptShowList = canShowList.slice(from, to);
    };

    $scope.showscriptList = function (currentPage,totalItem) {
        var perPage = $scope.paginationConf.itemsPerPage;
        var from = (currentPage - 1) * perPage;
        var to = (from + perPage)>totalItem?totalItem:from + perPage;
        console.log($scope.allscriptList);
        console.log(from)
        console.log(to)
        $scope.scriptShowList = $scope.allscriptList.slice(from, to);
        $scope.paginationConf.totalItems = totalItem ;
        console.log($scope.scriptShowList)
        console.log($scope.paginationConf.totalItems)
        $scope.filterList(currentPage);
    };
    $scope.downLoadScript = function (scriptInfo) {
        console.log(scriptInfo);
        var request = JSON.parse(JSON.stringify(scriptInfo));
        console.log(request);
        $http({
            method: "POST",
            url: "script/downLoadScript.do",
            data:request,
            responseType: 'arraybuffer'
        }).success(function (response, status, headers, config) { 
        	var fileName=headers('Content-Disposition');
	        fileName = decodeURI(fileName);
	        var url = URL.createObjectURL(new Blob([response]));
	        var a = document.createElement('a');
	        document.body.appendChild(a); //此处增加了将创建的添加到body当中
	        a.href = url;
	        a.download = fileName;
	        a.target = '_blank';
	        a.click();
	        a.remove(); //将a标签移除
        });
    };
    $scope.deleteScript= function (script) {
        $http({
            method: "POST",
            url: "script/deleteScript.do",
            params:{
                script:script
            }
        }).success(function (resp) {
            if(resp.status ==0){
                Notification.info({message: "delete success!", delay: 2000});
            }else {
                Notification.error({message: resp.errMsg, delay: 2000});
            }
        });
    };
    
    $scope.postUpdatescriptRequest = function (scriptRequestItem) {
            console.log(scriptRequestItem);
            var request = JSON.parse(JSON.stringify(scriptRequestItem));
            console.log(request);
            $http({
                method: "POST",
                url: "script/update.do",
                data:request
            }).success(function (resp) {
                if(resp.status ==0){
                	
                    $http({
                        method: "GET",
                        url: "script/list.query"
                    }).success(function (resp) {
                        if(resp.status ==0){
                            $scope.allscriptList = resp.data;
                            console.log($scope.allscriptList);
                            console.log(JSON.stringify(resp));
                            $scope.showscriptList(1,$scope.allscriptList.length);
                            $window.location.reload();
                        }else {
                            Notification.error({message: resp.errMsg, delay: 5000});
                        }

                    });
                }else {
                    Notification.error({message: resp.errMsg, delay: 2000});
                }
            });
            
        };
        function haveChineseBiaoDian(text)
        {
            //匹配这些中文标点符号 。 ？ ！ ， 、 ； ： “ ” ‘ ' （ ） 《 》 〈 〉 【 】 『 』 「 」 ﹃ ﹄ 〔 〕 … — ～ ﹏ ￥
            var reg = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
            if(reg.test(text)){
                return true;//是中文标点符号
            }else{
                return false;//不是中文标点符号
            }
        }
        
        function haveChinese(obj){
            if(/.*[\u4e00-\u9fa5]+.*$/.test(obj))
            {
                return true;
            }
            return false;
        }
        $scope.postscriptRequest = function (scriptRequestItem) {
        	debugger;
            console.log(scriptRequestItem);
            var request = JSON.parse(JSON.stringify(scriptRequestItem));
            console.log(request);
            if(request.versionCode==null || request.versionCode==''){
            	alert("版本号不能为空");
            	return;
            }
           
            if(request.regionName==null || request.regionName==''){
            	alert("域名不能为空");
            	return;
            }
            if(request.enviroCode==null || request.enviroCode==''){
            	alert("环境不能为空");
            	return;
            }
            if(request.cluster==null || request.cluster==''){
            	alert("集群名称不能为空");
            	return;
            }
            if(request.servUserName==null || request.servUserName==''){
            	alert("消息发送者不能为空");
            	return;
            }
            if(request.servUserName==null || request.servUserName==''){
            	alert("消息发送者不能为空");
            	return;
            }
            if(request.servOfferName==null || request.servOfferName==''){
            	alert("消息接收者不能为空");
            	return;
            }
            if(request.reqOrRes==null || request.reqOrRes==''){
            	alert("请求还是响应?");
            	return;
            }
            if(request.servCode==null || request.servCode==''){
            	alert("服务英文简称不能为空");
            	return;
            }
            
            if(haveChineseBiaoDian(request.servCode)){
            	alert("服务英文简称含有中文标点符号");
            	return;
            }
            if(haveChinese(request.servCode)){
            	alert("服务英文简称含有中文汉字");
            	return;
            }
            if(request.servName==null || request.servName==''){
            	alert("服务中文名称不能为空");
            	return;
            }
            $http({
                method: "POST",
                url: "script/save.do",
                data:request
            }).success(function (resp) {
                if(resp.status ==0){
                	
                    $http({
                        method: "GET",
                        url: "script/list.query"
                    }).success(function (resp) {
                        if(resp.status ==0){
                            $scope.allscriptList = resp.data;
                            $scope.showscriptList(1,$scope.allscriptList.length);
                            $window.location.reload();
                            Notification.info({message: "插入成功", delay: 2000});
                        }else {
                            Notification.error({message: resp.errMsg, delay: 5000});
                        }

                    });
                   
                }else {
                    Notification.error({message: resp.errMsg, delay: 2000});
                }
            });
        };


    $scope.consumerView = function (script) {
        $http({
            method: "GET",
            url: "script/queryConsumerByscript.query",
            params: {script: script}
        }).success(function (resp) {
            if (resp.status == 0) {
                console.log(JSON.stringify(resp));
                ngDialog.open({
                    template: 'consumerViewDialog',
                    data:{
                        script:script,
                        consumerData:resp.data,
                        consumerGroupCount:Object.keys(resp.data).length
                    }
                });
            }else {
                Notification.error({message: resp.errMsg, delay: 2000});
            }
        })
    };
    $scope.openDeletescriptDialog = function (script) {
        ngDialog.open({
            template: 'deletescriptDialog',
            controller: 'deletescriptDialogController',
            data:{
                script:script,
                consumerData:"asd"
            }
        });
    };



    $scope.openSendscriptMessageDialog = function (script) {
        ngDialog.open({
            template: 'sendscriptMessageDialog',
            controller: 'sendscriptMessageDialogController',
            data: {
                script: script
            }
        });
    };

    $scope.openUpdateDialog = function (script) {
        $http({
            method: "GET",
            url: "script/examinescriptConfig.query",
            params:{
                script:script
            }
        }).success(function (resp) {
            if(resp.status ==0){
                $scope.openCreateOrUpdateDialog(resp.data);
            }else {
                Notification.error({message: resp.errMsg, delay: 2000});
            }
        });
    };

    $scope.allSysNameList=[];
    $scope.allEnvNameList=[];
    $scope.allRegionNameList=[];
    $scope.allClusterList=[];
    $scope.reqOrRes=[{code:"REQUEST",name:"请求"},{code:"RESPONSE",name:"响应"}];
    $scope.openCreateScriptDialog = function (request) {
        var bIsUpdate = true;

        if(request == null){
            request = [{
            	regionName:"",
            	enviroCode:"",
            	cluster:"",
            	servUserName:"",
            	servOfferName:"",
            	servCode:"",
                servName:"",
                versionCode:"",
                reqOrRes:""
            }];
            bIsUpdate = false;
        }
        $http({
            method: "GET",
            url: "script/listSysAndEnv.query"
        }).success(function (resp) {
            if(resp.status ==0){
                console.log(resp.data);
                ngDialog.open({
                    template: 'scriptCreateDialog',
                    controller: 'scriptController',
                    data:{
                        scriptRequestList:request,
                        allSysNameList:resp.data.sysMap,
                        allEnvNameList:resp.data.envMap,
                        allRegionNameList:resp.data.regionMap,
                        allClusterList:resp.data.clusterMap,
                        reqOrRes:$scope.reqOrRes,
                        bIsUpdate:bIsUpdate
                    }
                });
            }
        });
    }

    $scope.openAddScriptDialog = function () {
        $scope.openCreateScriptDialog(null);
    }

    $scope.info={
        	regionName:"",
        	enviroCode:"",
        	cluster:"",
        	servUserName:"",
        	servOfferName:"",
        	servCode:"",
            servName:"",
            versionCode:"",
            reqOrRes:""
        };
    $scope.openModifyScriptDialog = function (id) {
        var bIsUpdate = false;
        $http({
            method: "POST",
            url: "script/findScriptInfoById.query",
        	 data: {
                 id: id
             }
        }).success(function (resp) {
            if(resp.status ==0){
                console.log(resp.data);
                $scope.info=resp.data.scriptInfo;
                debugger;
                ngDialog.open({
                    template: 'scriptModifyDialog',
                    controller: 'scriptController',
                    data:{
                    	item:resp.data.scriptInfoList,
                    	allSysNameList:resp.data.sysMap,
                        allEnvNameList:resp.data.envMap,
                        allRegionNameList:resp.data.regionMap,
                        allClusterList:resp.data.clusterMap,
                        reqOrRes:$scope.reqOrRes,
                        bIsUpdate:bIsUpdate
                    }
                });
            }
        });
    }
    
    
    $scope.discardInterface=function(id){
        var bIsUpdate = false;
        $http({
            method: "POST",
            url: "script/changestatus.do",
        	 data: {
                 id: id
             }
        }).success(function (resp) {
            if(resp.status ==0){
            	
            	 $http({
                     method: "GET",
                     url: "script/list.query"
                 }).success(function (resp) {
                     if(resp.status ==0){
                         $scope.allscriptList = resp.data;
                         console.log($scope.allscriptList);
                         console.log(JSON.stringify(resp));
                         $scope.showscriptList(1,$scope.allscriptList.length);
                        
                     }else {
                         Notification.error({message: resp.errMsg, delay: 5000});
                     }

                 });
            	 $scope.filterList(1);
            }
        });
    }
    
    function StringBuffer() {
        this.__strings__ = [];
    };
    StringBuffer.prototype.append = function(str) {
        this.__strings__.push(str);
    };
    StringBuffer.prototype.toString = function() {
        return this.__strings__.join('');
    };
    
    $scope.handleArrays=function(consumerGroup){
    	var buffer = new StringBuffer();//声明一个对象
       
    	//alert(consumerGroup);
    	var obj=[];
        var result = "";
    	obj = JSON.parse(consumerGroup); //由JSON字符串转换为JSON对象
    	
    	for(var i=0;i<obj.length;i++){
    		if(obj.length>1){
    			buffer.append(i+1+"."+obj[i]+"、");//追加字符串，下同
    		}else{ 
    			buffer.append(obj[i]+"、");//追加字符串，下同}
    		}
    		
    		// buffer.append('。');//追加字符串，下同
    		// result+=(i+1+"."+obj[i]+"");
    	}
    	//alert(date.replace(/(。)(\d)/g,"$1\n$2"));
    	return buffer.toString().substr(0, buffer.toString().length-1);;
    	//return result;
    }
}]);


